import { AllHTMLAttributes, createElement, type FC } from 'react';
import classNames from 'classnames';

import { menuItemDefaultProps } from './defaultProps';
import type { MenuItemOptions } from './type';
import { useMenuContext } from './MenuContext';

export interface MenuItemProps extends MenuItemOptions, Omit<AllHTMLAttributes<HTMLElement>, 'as'> {}

const MenuItem: FC<MenuItemProps> = (props) => {
  const { className, as, id, active, forwardedRef, children, ...menuItemProps } = props;

  const [state, setState] = useMenuContext();

  const handleClick = () => {
    setState({ activeItem: id });
  };

  return createElement(
    as!,
    {
      ref: forwardedRef,
      id,
      className: classNames('item', { active: id ? id === state.activeItem : active }, className),
      onClick: handleClick,
      ...menuItemProps,
    },
    children,
  );
};

MenuItem.displayName = 'MenuItem';
MenuItem.defaultProps = menuItemDefaultProps;

export default MenuItem;
